package com.songcha.sakura.mvp.view.dialog

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.*
import android.widget.FrameLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.songcha.library_common.util.ScreenUtil
import com.songcha.library_common.util.StatusBarUtil
import com.songcha.library_common.util.dp2px
import com.songcha.sakura.R
import com.songcha.sakura.bean.ComicDetailBean
import com.songcha.sakura.bean.ComicListBean
import com.songcha.sakura.ui.adapter.ComicPlayUrlAdapter
import com.songcha.sakura.databinding.BottomsheetComicDetailBinding
import com.songcha.sakura.mvp.contract.ComicDetailContract
import com.songcha.sakura.mvp.presenter.ComicDetailDialogPresenter
import com.songcha.library_common.ui.view.CustomTabLayout


//var mContext: Context,val mComic: ComicListBean.ComicBean
class ComicDetailDialogP : BaseBottomSheetDialogFragmentP<ComicDetailDialogPresenter>() , ComicDetailContract.View{
    private var mComic: ComicListBean.ComicBean?=null
    private val mPeekHeightScale=0.7

    companion object{
        //@JvmStatic
        //private var mFm:FragmentManager?=null
    }


    private lateinit var mBinding:BottomsheetComicDetailBinding


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStyle(STYLE_NORMAL, R.style.bottom_sheet_dialog)

        arguments?.let {
            //mContext=this@ComicDetailDialogP.context
            mComic=it.getSerializable("comic") as ComicListBean.ComicBean
        }


    }

    //fun initCtx(ctx:Context){
       // mContext=ctx
        //mBinding= BottomsheetComicDetailBinding.inflate(layoutInflater,null,false)
   // }




    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        //LogUtil.log("onCreateView")

        mBinding=BottomsheetComicDetailBinding.inflate(layoutInflater,container,false)

        com.songcha.sakura.mvp.component.DaggerComicDetailComponent.builder().view(this).build().inject(this)

        presenter.getComicDetail(mComic!!.href)

        //return mView

        return mBinding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // LogUtil.log("onViewCreated")

    }


    override fun onAttach(context: Context) {
        super.onAttach(context)
        //LogUtil.log("onAttach")
    }

    override fun onDetach() {
        super.onDetach()
        //LogUtil.log("onDetach")
    }

    override fun onStop() {
        super.onStop()
        //LogUtil.log("onStop")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        //LogUtil.log("onDestroyView")
    }

    override fun onPause() {
        super.onPause()
        //LogUtil.log("onPause")
    }


    fun getState(s:Int):String{
        when(s){
            BottomSheetBehavior.STATE_HIDDEN->return "STATE_HIDDEN"
            BottomSheetBehavior.STATE_DRAGGING->return "STATE_DRAGGING"
            BottomSheetBehavior.STATE_COLLAPSED->return "STATE_COLLAPSED"
            BottomSheetBehavior.STATE_EXPANDED->return "STATE_EXPANDED"
            BottomSheetBehavior.STATE_HALF_EXPANDED->return "STATE_HALF_EXPANDED"
            BottomSheetBehavior.STATE_SETTLING->return "STATE_SETTLING"
        }
        return ""
    }

/*  1.STATE_DRAGGING：过渡状态此时用户正在向上或者向下拖动bottom sheet
    2.STATE_SETTLING：视图从脱离手指自由滑动到最终停下的这一小段时间
    3.STATE_EXPANDED：处于完全展开的状态
    4.STATE_COLLAPSED：默认的折叠状态
    5.STATE_HIDDEN：下滑到完全隐藏 bottom sheet
    6.STATE_HALF_EXPANDED滑动到mHeight一半的距离*/

    override fun onStart() {
        //LogUtil.log("onStart")
        super.onStart()
        //

        StatusBarUtil.setStatusBarStyle(requireActivity(),true)

        val dialogBehavior = BottomSheetBehavior.from(mBinding.root.parent as View)
        //这里要用applictionContext,因为横屏切换的时候activity宽高会变
        dialogBehavior.peekHeight = (ScreenUtil.getScreenHeight(com.songcha.sakura.MyApplication.getContext())*mPeekHeightScale).toInt()
        dialogBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
            override fun onStateChanged(view: View, i: Int) {

                if (i == BottomSheetBehavior.STATE_HIDDEN) {
                    dismiss()
                    dialogBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                }
            }

            override fun onSlide(view: View, v: Float) {}
        })


       /*dialog?.window?.apply {
           // 1.修改window的高度
           setLayout(-1, -1) // ViewGroup.LayoutParams.MATCH_PARENT
           // 2.修改容器的高度
           decorView.findViewById<FrameLayout>(com.google.android.material.R.id.design_bottom_sheet)?.apply {
               layoutParams.height = -1
               layoutParams.width = -1
           }
           // 3.设置状态为展开
           dialogBehavior.state = BottomSheetBehavior.STATE_COLLAPSED

        }*/

    }


    override fun onDestroy() {
        //LogUtil.log("onDestroy")
        super.onDestroy()
    }



    override fun onResume() {
        //LogUtil.log("onResume")
        super.onResume()
    }



   /* private  fun getData(){
        //mView.findViewById<>()
        viewModel.getComicDetail(mComic.href,this)

    }*/



    private fun initData(bean: ComicDetailBean){
       // LogUtil.log("initData",isAdded)
        if(!isAdded) return

         //mBinding.comic=bean
        mBinding.tvTitle.text=bean.title
        mBinding.tvScore.text=bean.score
        mBinding.tvDoubanScore.text=bean.doubanScore
        mBinding.tvUpdate.text=bean.update
        mBinding.tvDirector.text=bean.director
        mBinding.tvCate.text=bean.cate
        mBinding.tvYear.text=bean.year

        try {
            if(bean.doubanScore.toFloat()>=8.5f){
                mBinding.tvDoubanScore.setTextColor(Color.parseColor("#ffb400"))
            }else if(bean.doubanScore.toFloat()<5){
                mBinding.tvDoubanScore.setTextColor(Color.parseColor("#cccccc"))
            }
        }catch (e:Exception){
            e.printStackTrace()
        }

         Glide.with(requireContext()).load(bean.thumb).into(mBinding.ivThumb)

         mBinding.tvActors.text=bean.actors.joinToString(" ")

         val ctl=mBinding.root.findViewById<CustomTabLayout>(R.id.ctl_play_url)

         mBinding.tvBrief.text=bean.brief
         mBinding.tvBrief.setOnClickListener {
             it as TextView
             if (it.text == bean.brief) {
                 if(bean.briefAll.isEmpty()){
                     it.text = "unknow"
                 }else{
                     it.text = bean.briefAll
                 }

             } else {
                 it.text = bean.brief
             }
         }


         mBinding.vp.adapter=ComicPlayUrlAdapter(this.childFragmentManager,bean.thumb, bean.playSource,bean.playUrlList)

         ctl.setViewPager(mBinding.vp)

    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        //LogUtil.log("onActivityCreated")
        super.onActivityCreated(savedInstanceState)
    }


   override fun onLoading() {
        val ivLoading=mBinding.ivLoading
        Glide.with(requireContext()).asGif().load(R.drawable.icon_loading).into(ivLoading)

        (ivLoading.layoutParams as FrameLayout.LayoutParams).setMargins(0,
            ((ScreenUtil.getScreenHeight(requireContext())*mPeekHeightScale-100f.dp2px())/2).toInt(),0,0)
        ivLoading.visibility=View.VISIBLE
        mBinding.clDetail.visibility=View.INVISIBLE

    }

    override fun onLoadSuccess() {
        val ivLoading=mBinding.ivLoading
        ivLoading.visibility=View.GONE
        mBinding.clDetail.visibility=View.VISIBLE
    }

    override fun onLoadError(e:Throwable) {
        val ivLoading=mBinding.ivLoading
        Glide.with(requireContext()).load(com.songcha.sakura.R.drawable.icon_error).into(ivLoading)

        (ivLoading.layoutParams as FrameLayout.LayoutParams).setMargins(0,
            ((ScreenUtil.getScreenHeight(requireContext())*mPeekHeightScale-100f.dp2px())/2).toInt(),0,0)
        ivLoading.visibility=View.VISIBLE
        mBinding.clDetail.visibility=View.INVISIBLE
    }

    override fun onComicDetail(data:ComicDetailBean) {
        initData(data)
    }

}